package cn.itsource.user.service.impl;

import cn.itsource.basic.domain.VerificationConstant;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.MD5Utils;
import cn.itsource.basic.util.StrUtils;
import cn.itsource.user.domain.LoginInfo;
import cn.itsource.user.domain.LogininfoDto;
import cn.itsource.user.domain.User;
import cn.itsource.user.mapper.LoginInfoMapper;
import cn.itsource.user.mapper.UserMapper;
import cn.itsource.user.service.ILoginInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginInfoServiceImpl extends BaseServiceImpl<LoginInfo> implements ILoginInfoService{
    @Autowired
    private LoginInfoMapper mapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    RedisTemplate redisTemplate;


    //登录
    @Override
    public AjaxResult querybyusernameandtype(LogininfoDto logininfoDto) throws Exception {
        //验证
        ClikeLogindata(logininfoDto);
        LoginInfo loginInfo = mapper.querybyusernameandtype(logininfoDto.getUsername(),logininfoDto.getType());
        if(loginInfo == null){
            throw  new Exception("没有该用户");
        }
        if(!loginInfo.getPassword().equals(MD5Utils.encrypByMd5(logininfoDto.getPassword()+loginInfo.getSalt()))){
            throw  new  Exception("密码错误");
        }
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token, loginInfo,30, TimeUnit.MINUTES);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("token", token);
        hashMap.put("loginUser", loginInfo);
        return new AjaxResult().setResultObj(hashMap);

    }

    private void ClikeLogindata(LogininfoDto logininfoDto) throws Exception {
        if(StringUtils.isEmpty(logininfoDto.getUsername())){
            throw  new  Exception("用户名不能为空");
        }
        if(StringUtils.isEmpty(logininfoDto.getPassword())){
            throw  new  Exception("密码不能为空");
        }
        if(logininfoDto.getType() == null){
            throw  new  Exception("请完善登录资料");
        }
    }

    @Override
    @Transactional
    public void addreg(LogininfoDto loginInfodto) throws Exception {
        //校验
        checkData(loginInfodto);
        //创建保存login info
        LoginInfo loginInfo = creatLoginfo(loginInfodto);
        mapper.add(loginInfo);
        //创建保存user
        User user = creatUser(loginInfo);
        userMapper.add(user);
    }


    private User creatUser(LoginInfo loginInfo) {
        User user = new User();
        BeanUtils.copyProperties(loginInfo, user);
        user.setState(1);
        user.setLogininfo(loginInfo);
        return user;
    }

    private LoginInfo creatLoginfo(LogininfoDto loginInfodto) {
        LoginInfo info = new LoginInfo();
        //盐值
        info.setSalt(StrUtils.getComplexRandomString(6));
        //手机
        info.setPhone(loginInfodto.getPhone());
        //类型
        info.setType(loginInfodto.getType());
        //密码
        info.setPassword(MD5Utils.encrypByMd5(loginInfodto.getPassword()+info.getSalt()));
        return info;
    }

    public void checkData(LogininfoDto loginInfodto) throws Exception {
        //密码为空
        if(StringUtils.isEmpty(loginInfodto.getPassword())){
            throw  new Exception("密码为空");
        }
        //判断重复密码
        if(StringUtils.isEmpty(loginInfodto.getRepassword())){
            throw  new Exception("重复密码不能为空");
        }
        //判断两次密码是否一致
        if(!loginInfodto.getPassword().equals(loginInfodto.getRepassword())){
            throw  new Exception("两次密码不一致");
        }
        //点换号码
        if(StringUtils.isEmpty(loginInfodto.getPhone())){
            throw  new Exception("电话号码不能为空");
        }
        //电话号码是否正确
        User user = userMapper.finduserbypassword(loginInfodto.getPhone());
        if(user!= null){
            throw  new Exception("手机号已经注册了");
        }
        //判断验证码
        if(loginInfodto.getCode()==null || loginInfodto.getCode().equals("")){
            throw  new Exception("验证码不能为空");
        }
        String valecode = (String) redisTemplate.opsForValue().get(loginInfodto.getPhone() + ":" + VerificationConstant.USER_REG);
         if(StringUtils.isEmpty(valecode)){
             throw  new  Exception("验证码已过期，请重新获取");
         }
         if(loginInfodto.getCode().equals(valecode.split(":")[0])){
             throw  new  Exception("验证码不正确");
         }
        System.out.println(valecode.split(":")[0]);
    }
}
